package cfca.seal.web.system;

import cfca.com.itextpdf.text.pdf.security.TSAClientBouncyCastle;
import cfca.seal.mananger.CrlManager;
import cfca.seal.mananger.PdfSealManager;
import cfca.seal.mananger.SealCertManager;
import cfca.seal.mananger.SealManager;
import cfca.seal.mananger.TrustCertManager;
import cfca.seal.system.Env;
import cfca.seal.util.StringUtil;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class SystemListener
  implements ServletContextListener
{
  private static Logger sysLogger = LoggerFactory.getLogger("web_sys");

  public void contextDestroyed(ServletContextEvent sce)
  {
  }

  public void contextInitialized(ServletContextEvent servletContextEvent)
  {
    try
    {
      sysLogger.info("初始化系统开始");
      String path = servletContextEvent.getServletContext().getInitParameter("system.config.path");
      Env.configDir = path;
      sysLogger.info("配置文件路径：" + Env.configDir);

      Properties properties = new Properties();
      properties.load(new FileInputStream(Env.configDir + File.separator + "sys.ini"));

      Object version = properties.get("version");
      if (null != version)
        Env.version = version.toString();
      sysLogger.info("系统的版本号: " + Env.version);

      Object imageWidthLimit = properties.get("imageWidthLimit");
      if (null != imageWidthLimit)
        Env.imageWidthLimit = Integer.parseInt(imageWidthLimit.toString());
      sysLogger.info("上传电子印章图片的最大宽度: " + Env.imageWidthLimit);

      Object imageHeightLimit = properties.get("imageHeightLimit");
      if (null != imageHeightLimit)
        Env.imageHeightLimit = Integer.parseInt(imageHeightLimit.toString());
      sysLogger.info("上传电子印章图片的最大高度: " + Env.imageHeightLimit);

      Object timeStampServerUrl = properties.get("timeStampServerUrl");
      if (null != timeStampServerUrl)
        Env.timeStampServerUrl = timeStampServerUrl.toString();
      sysLogger.info("时间戳服务器配置的URL: " + Env.timeStampServerUrl);

      Object timeStampServerUser = properties.get("timeStampServerUser");
      if (null != timeStampServerUser)
        Env.timeStampServerUser = timeStampServerUser.toString();
      sysLogger.info("时间戳服务器配置的用户名: " + Env.timeStampServerUser);

      Object timeStampServerPasswd = properties.get("timeStampServerPasswd");
      if (null != timeStampServerPasswd)
        Env.timeStampServerPasswd = timeStampServerPasswd.toString();
      sysLogger.info("时间戳服务器配置的密码: " + Env.timeStampServerPasswd);

      if (StringUtil.isNotEmpty(Env.timeStampServerUrl)) {
        Env.tsaClient = new TSAClientBouncyCastle(Env.timeStampServerUrl, Env.timeStampServerUser, Env.timeStampServerPasswd);
        sysLogger.info("时间戳服务器配置成功");
      }

      Object specialChar = properties.get("specialChar");
      if (null != specialChar)
        Env.specialChar = specialChar.toString();
      sysLogger.info("特殊字符: " + Env.specialChar);

      Object databaseType = properties.get("databaseType");
      if (null != databaseType)
        Env.databaseType = databaseType.toString();
      sysLogger.info("数据库类型: " + Env.databaseType);

      Object overdueDays = properties.get("overdueDays");
      if (null != overdueDays)
        Env.overdueDays = overdueDays.toString();
      sysLogger.info("证书过期提醒提前天数: " + Env.overdueDays);

      Object signAlg = properties.get("signAlg");
      if (null != signAlg)
        Env.signAlg = signAlg.toString();
      sysLogger.info("二维码签名证书类型: " + Env.signAlg);

      Object openOfficeIP = properties.get("openOfficeIP");
      if (null != openOfficeIP)
        Env.openOfficeIP = openOfficeIP.toString();
      sysLogger.info("openOffice地址: " + Env.openOfficeIP);

      Object openOfficePort = properties.get("openOfficePort");
      if (null != openOfficePort)
        Env.openOfficePort = openOfficePort.toString();
      sysLogger.info("openOffice端口: " + Env.openOfficePort);

      String trustCertDir = Env.configDir + File.separator + "cert";
      File trustCertDirFile = new File(trustCertDir);
      if (!trustCertDirFile.exists()) {
        trustCertDirFile.mkdirs();
      }
      TrustCertManager.trustCertPath = trustCertDir + File.separator + "trustCert.p7b";
      TrustCertManager.instance.init();
      sysLogger.info("信任证书管理器初始化目录: " + trustCertDir);

      String crlDir = Env.configDir + File.separator + "crl";
      File crlDirFile = new File(crlDir);
      if (!crlDirFile.exists()) {
        crlDirFile.mkdirs();
      }
      CrlManager.cacheOrRefreshCrl(crlDir);
      sysLogger.info("CRL管理器初始化目录: " + crlDir);

      Object crlSourceFiles = properties.get("CRLSourceFiles");
      if ((null != crlSourceFiles) && (StringUtil.isNotEmpty(crlSourceFiles.toString())))
        Env.CRLSourceFiles = crlSourceFiles.toString();
      sysLogger.info("CRL更新源文件(CRL更新定时任务): " + Env.CRLSourceFiles);

      Object swKeyIndexMax = properties.get("swKeyIndexMax");
      if ((null != swKeyIndexMax) && (StringUtil.isNotEmpty(swKeyIndexMax.toString())))
        Env.swKeyIndexMax = swKeyIndexMax.toString();
      sysLogger.info("三未加密机密钥对数量 " + Env.CRLSourceFiles);

      Env.applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext());

      if ("sqlite".equals(Env.databaseType))
      {
        PdfSealManager.getInstance().init(servletContextEvent.getServletContext());
        SealManager.getInstance().init(servletContextEvent.getServletContext());
        SealCertManager.getInstance().init(servletContextEvent.getServletContext());
      }

      sysLogger.info("初始化系统成功");
    } catch (Exception e) {
      sysLogger.error("初始化系统失败", e);
      System.exit(0);
    }
  }
}